package com.mark.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

public class JsonUtil {
    private static ObjectMapper mapper = createObjectMapper();

    private static ObjectMapper createObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }

    public static String bean2Json(Object object) {
        try {
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (Exception e) {
            System.out.println(e);
            return "";
        }
    }

    public static <T> T json2Bean(String jsonStr, Class<T> clazz) {
        try {
            return mapper.readValue(jsonStr, clazz);
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    public static <T> T json2Bean(String jsonStr, TypeReference<T> objClass) {
        try {
            return mapper.readValue(jsonStr, objClass);
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    public static String list2String(List<String> array) {
        return JsonUtil.bean2Json(array);
    }

    public static List<String> string2List(String json) {
        return JsonUtil.json2Bean(json, new TypeReference<List<String>>() {
        });
    }

    public static String format(String json){
        return JsonUtil.bean2Json(JsonUtil.json2Bean(json, Map.class));
    }
}